﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
    public static class ConversionHelpers
    {
        /// <summary>
        /// Converts a Unix Time Stamp to a DateTime
        /// </summary>
        /// <param name="unixTimeStamp">Unix Time Stamp (string)</param>
        /// <returns>DateTime of Unix Time Stamp</returns>
        public static DateTime? ConvertUnixTimeStamp(string unixTimeStamp)
        {
            return new DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(Convert.ToDouble(unixTimeStamp));
        }

        /// <summary>
        /// Gets the average of a list of doubles, ignores null
        /// </summary>
        /// <param name="Values">List of values</param>
        /// <returns>Average (Default 0)</returns>
        public static double GetAverage(List<double?> Values)
        {
            double retVal = 0;
            List<double> values = new List<double>();
            foreach (double? value in Values)
            {
                if (value != null)
                    values.Add(value ?? 0);
            }

            if (values.Count > 0)
            {
                retVal = values.Average();
            }

            return retVal;
        }

        /// <summary>
        /// Gets the standard deviation of a list of doubles, ignores null
        /// </summary>
        /// <param name="Values">List of values</param>
        /// <returns>Average (Default 0)</returns>
        public static double GetStandardDeviation(List<double?> Values)
        {
            double retVal = 0;
            List<double> values = new List<double>();
            foreach (double? value in Values)
            {
                if (value != null)
                    values.Add(value ?? 0);
            }

            if (values.Count > 1)
            {
                //Compute the Average      
                double avg = values.Average();
                //Perform the Sum of (value-avg)_2_2      
                double sum = values.Sum(d => Math.Pow((d - avg), 2));
                //Put it all together 
                retVal = Math.Sqrt((sum) / (values.Count()));
            }

            return retVal;
        }
    }
}
